package com.lzy.wzy.provider;


import com.lzy.wzy.config.MyPasswordEncoder;
import com.lzy.wzy.exception.DepartmentSelectionException;
import com.lzy.wzy.model.UserBean;
import com.lzy.wzy.service.imp.UserServiceImp;
import com.lzy.wzy.token.MyUsernamePasswordToken;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.*;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.stereotype.Component;

@Slf4j
@Component
public class MyAuthenticationProvider implements AuthenticationProvider {
    @Autowired
    private UserServiceImp userServiceImp;

    @Autowired
    private MyPasswordEncoder myPasswordEncoder;


    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        String username = authentication.getName();
        String password = (String) authentication.getCredentials();
        UserBean user = (UserBean) userServiceImp.loadUserByUsername(username);
        if (!user.isEnabled()) {
            throw new DisabledException("该账户已被禁用，请联系管理员");

        } else if (!user.isAccountNonLocked()) {
            throw new LockedException("该账号已被锁定");

        } else if (!user.isAccountNonExpired()) {
            throw new AccountExpiredException("该账号已过期，请联系管理员");

        } else if (!user.isCredentialsNonExpired()) {
            throw new CredentialsExpiredException("该账户的登录凭证已过期，请重新登录");
        }
//        if (!checkUtils.isPasswordOk(password)) {
//            throw new BadCredentialsException("密码格式有误!");
//        }
        //验证密码
        if (!myPasswordEncoder.matches(password, user.getPassword())) {
            throw new BadCredentialsException("输入密码错误!");
        }
        return new MyUsernamePasswordToken(user, password, user.getAuthorities());
    }


    @Override
    public boolean supports(Class<?> authentication) {
        // 判断 authentication 是不是 AuthenticationToken 的子类或子接口
        return MyUsernamePasswordToken.class.isAssignableFrom(authentication);
    }
}
